import Menu from '@/api/menu'

export const initMenu = (router, store)=>{
  if (store.state.routes.length > 0){
    return;
  }
  // 请求获取菜单
  Menu.getMenu().then((res) => {
    console.log("菜单请求中。。。。。。")
    if (res){
      console.log(res.data);
      // 格式化router
      let fmtRoutes = formatRoutes(res.data)
      // 添加路由
      // router.matcher.addRoutes(fmtRoutes)
      router.addRoutes(fmtRoutes)
      console.log("hhh");
      console.log(router);
      // console.log(router.addRoutes(fmtRoutes));
      // 将路由存储vuex
      store.commit('initRoutes', fmtRoutes);
      // 连接websocket
      store.dispatch('connect');
    }
  }).catch(error => {
    console.log(error);
  })
}

export const formatRoutes = (routes) => {
  let fmtRoutes = [];
  routes.forEach((router) => {
    let{
      path,
      component,
      name,
      iconCls,
      children,
    } = router;
    if (children && children instanceof Array){
      // 递归
      children = formatRoutes(children);
    }
    let fmtRouter = {
      path: path,
      name: name,
      iconCls: iconCls,
      children: children,
      component:(resolve) => {
        if (component.startsWith('Home')){
          require(['../views/home/'+component+'.vue'], resolve)  //懒加载
        } else if (component.startsWith('Emp')) {
          require(['../views/employee/'+component+'.vue'], resolve)  //懒加载
        } else if (component.startsWith('Sign')) {
          require(['../views/sign/'+component+'.vue'], resolve)  //懒加载
        } else if (component.startsWith('Sys')) {
          require(['../views/system/'+component+'.vue'], resolve)  //懒加载
        } else if (component.startsWith('Pro')) {
          require(['../views/apply/'+component+'.vue'], resolve)  //懒加载
        } else if (component.startsWith('Fri')){
          require(['../views/chat/'+component+'.vue'], resolve)  //懒加载
        } else if (component.startsWith('Task')){
          require(['../views/task/'+component+'.vue'], resolve)  //懒加载
        }
      }
    }
    fmtRoutes.push(fmtRouter);
  });

  return fmtRoutes;
}
